package com.symaster.common.test.animation;

import com.symaster.common.animation.Animation;
import com.symaster.common.animation.Curve;
import com.symaster.common.geom.entity.Point;
import com.symaster.common.swing.FpsManager;
import com.symaster.common.swing.util.SwingUtil;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author yinmiao
 * @version 2023/11/27
 */
public class AnimationTest4 {

    public static void main(String[] args) throws InterruptedException {
        final Animation animation = new Animation();

        Canvas canvas = new Canvas();

        JFrame jFrame = new JFrame("AnimationTest4");
        jFrame.setPreferredSize(new Dimension(900,450));
        jFrame.setContentPane(canvas);
        jFrame.pack();
        jFrame.setVisible(true);
        SwingUtil.toCenter(jFrame);

        TimeUnit.SECONDS.sleep(2);
        animation.execution(Animation.Sequence.SEQUENCE_TURN, Animation.Strategy.Stop, new Animation.AnimationListener(Curve.TYPE_FAST_TO_SLOW_TO_FAST, Animation.AnimationConfig.ofTime(1000, 1, 0)) {
            @Override
            public void handler(double factor) {
                canvas.pointList.add(new Point(time(), factor));
            }
        });
    }

    private static double time() {
        return System.nanoTime() / 1000000.0;
    }

    private static class Canvas extends JComponent {

        private final FpsManager fpsManager = new FpsManager();
        public final List<Point> pointList = new ArrayList<>();

        public float timeRange = 1000;

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            int width = getWidth() - 1;
            int height = getHeight() - 1;

            g.setColor(new Color(255, 0, 0));

            if (pointList.size() > 2) {
                ArrayList<Point> points = new ArrayList<>(pointList);
                double startTime = points.get(0).x;

                for (int i = 0; i < points.size() - 1; i++) {
                    Point s1 = points.get(i);
                    Point s2 = points.get(i + 1);

                    double x1 = (s1.x - startTime) / timeRange * width;
                    double y1 = s1.y * height;

                    double x2 = (s2.x - startTime) / timeRange * width;
                    double y2 = s2.y * height;

                    g.drawLine(Math.round((float) x1), Math.round((float) y1), Math.round((float) x2), Math.round((float) y2));
                }
            }

            fpsManager.paintRunnable(120, this::repaint);
        }
    }

}
